<template>
	<view class="qrcode">
		<view class="imgbox">
			<view class="qrcode">
				<image :src="qrcode" v-if="qrcode" mode=""></image>
			</view>
			<view class="btnbox">
				<button type="primary" @click="SaveImage">保存到相册</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				qrcode: "",
			}
		},
		computed: {
			token() {
				return this.$store.state.token;
			},
			UserInfo() {
				return this.$store.state.UserInfo
			}
		},
		onLoad() {
			this.getCodeImage()
		},
		methods: {
			// 检测用户是否有二维码,如果没有就自动生成
			async getCodeImage() {
				let res = await this.$Request("/admin/getqrCode", "", this.token)
				// console.log(res);
				let code = res.data.code 
				if(code == 200) {
					this.qrcode = res.data.data
					console.log(this.qrcode);
				} else {
					let data = {
						path: `/pages/my/my?id=${this.UserInfo._id}`,
						width: 400,
					}
					console.log(data);
					 let ret = await this.$Request("/admin/createCode", data, this.token)
					 let ercode = ret.data.code
					 if(ercode == 200) {
						 this.qrcode = res.data.data
					 }
				}
			},
			
			// 保存图片到相册
			SaveImage() {
				let self = this
				if(this.qrcode) {
					uni.downloadFile({
						url: self.qrcode,
						success( res ) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success() {
									uni.showToast({
										title: "保存成功",
										icon: "success",
										duration: 2000
									})
								}
							})
						}
					})
				}
			},
		},
	}
</script>

<style scoped lang="scss">
	.qrcode {
		width: 100%;
		box-sizing: border-box;
		padding-top: 20%;
		.imgbox {
			width: 100%;
			box-sizing: border-box;
			text-align: center;
			padding: 20rpx;
			.qrcode {
				width: 400rpx;
				height: 400rpx;
				box-shadow: 0 0 5px #aaa;
				overflow: hidden;
				margin:  10rpx auto;
				image {
					width: 400rpx;
					height: 400rpx;
				}
			}
			.btnbox {
				padding: 20rpx;
				width: 100%;
				box-sizing: border-box;
				button {
					width: 400rpx;
					border-radius: 60rpx;
					font-size: 28rpx;
				}
			}
		}
	}
</style>
